package capture;

import capture.filter.BmpFilter;
import capture.filter.GifFilter;
import capture.filter.JpgFilter;
import capture.filter.PngFilter;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * 一个内部类,它表示一个面板,一个可以被放进tabpane的面板
 * 也有自己的一套处理保存和复制的方法
 */
public class PicPanel extends JPanel implements ActionListener {

    private final MainPanel capture;
    /** 得到的图片 */
    private BufferedImage image;
    /** 表示保存,复制,关闭的按钮 */
    private JButton save, copy, close;

    public PicPanel(MainPanel capture, BufferedImage image) {
        super(new BorderLayout());
        this.capture = capture;
        this.image = image;
        initPanel();
    }

    private void initPanel() {
        save = new JButton("保存(S)");
        copy = new JButton("复制到剪帖板(C)");
        close = new JButton("关闭(X)");
        save.setMnemonic('S');
        copy.setMnemonic('C');
        close.setMnemonic('X');
        JPanel buttonPanel = new JPanel();
        buttonPanel.add(copy);
        buttonPanel.add(save);
        buttonPanel.add(close);
        JLabel icon = new JLabel(new ImageIcon(image));
        this.add(new JScrollPane(icon), BorderLayout.CENTER);
        this.add(buttonPanel, BorderLayout.SOUTH);
        save.addActionListener(this);
        copy.addActionListener(this);
        close.addActionListener(this);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        Object source = e.getSource();
        if (source == save) {
            doSave();
        } else if (source == copy) {
            doCopy();
        } else if (source == close) {
            image = null;
            doClose();
        }
    }

    /**
     * 公用的处理保存图片的方法
     */
    public void doSave() {
        try {
            if (image == null) {
                JOptionPane.showMessageDialog(this
                        , "图片不能为空!!", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            JFileChooser jfc = new JFileChooser(".");
            jfc.addChoosableFileFilter(new GifFilter());
            jfc.addChoosableFileFilter(new BmpFilter());
            jfc.addChoosableFileFilter(new JpgFilter());
            jfc.addChoosableFileFilter(new PngFilter());
            int i = jfc.showSaveDialog(this);
            if (i == JFileChooser.APPROVE_OPTION) {
                File file = jfc.getSelectedFile();
                String about = "PNG";
                String ext = file.toString().toLowerCase();
                javax.swing.filechooser.FileFilter ff = jfc.getFileFilter();
                if (ff instanceof JpgFilter) {
                    if (!ext.endsWith(".jpg")) {
                        String ns = ext + ".jpg";
                        file = new File(ns);
                        about = "JPG";
                    }
                } else if (ff instanceof PngFilter) {
                    if (!ext.endsWith(".png")) {
                        String ns = ext + ".png";
                        file = new File(ns);
                        about = "PNG";
                    }
                } else if (ff instanceof BmpFilter) {
                    if (!ext.endsWith(".bmp")) {
                        String ns = ext + ".bmp";
                        file = new File(ns);
                        about = "BMP";
                    }
                } else if (ff instanceof GifFilter) {
                    if (!ext.endsWith(".gif")) {
                        String ns = ext + ".gif";
                        file = new File(ns);
                        about = "GIF";
                    }
                }
                if (ImageIO.write(image, about, file)) {
                    JOptionPane.showMessageDialog(this, "保存成功！");
                } else {
                    JOptionPane.showMessageDialog(this, "保存失败！");
                }
            }
        } catch (Exception exe) {
            exe.printStackTrace();
        }
    }

    /**
     * 公共的处理把当前的图片加入剪帖板的方法
     */
    public void doCopy() {
        try {
            if (image == null) {
                JOptionPane.showMessageDialog(this
                        , "图片不能为空!!", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            Transferable trans = new Transferable() {
                @Override
                public DataFlavor[] getTransferDataFlavors() {
                    return new DataFlavor[]{DataFlavor.imageFlavor};
                }

                @Override
                public boolean isDataFlavorSupported(DataFlavor flavor) {
                    return DataFlavor.imageFlavor.equals(flavor);
                }

                @Override
                public Object getTransferData(DataFlavor flavor)
                        throws UnsupportedFlavorException, IOException {
                    if (isDataFlavorSupported(flavor)) {
                        return image;
                    }
                    throw new UnsupportedFlavorException(flavor);
                }
            };

            Toolkit.getDefaultToolkit().getSystemClipboard().setContents(trans, null);
            JOptionPane.showMessageDialog(this, "已复制到系统粘帖板!!");
        } catch (Exception exe) {
            exe.printStackTrace();
            JOptionPane.showMessageDialog(this
                    , "复制到系统粘帖板出错!!", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    /**
     * 处理关闭事件
     */
    private void doClose() {
        capture.removePicPanel(this);
        System.gc();
    }
}
